using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Extra.ERP;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Forms;
using APP.HELPER.Data.Helper;
namespace Extra.Data.Extra.Class
{
    public class DataController
    {
        private static string _mConnectString = "Data Source=(local);Initial Catalog=master;Integrated Security=True";

        public event AttachCompleteEventHander AttachComplete;

        public event AttachErrorEventHander AttachError;

        public event BackupCompleteEventHander BackupComplete;

        public event BackupErrorEventHander BackupError;

        public event BackupProcessEventHander BackupProcess;

        public event CreatedCompleteEventHander CreatedComplete;

        public event CreatedErrorEventHander CreatedError;

        public event CreatedProcessEventHander CreatedProcess;

        private event DatabaseCompleteEventHander DatabaseComplete;

        private event DatabaseErrorEventHander DatabaseError;

        private event DatabaseFoundEventHander DatabaseFound;

        public event DatabasePercentEventHander DatabasePercent;

        public event DeletedCompleteEventHander DeletedComplete;

        public event DeletedErrorEventHander DeletedError;

        public event DetachCompleteEventHander DetachComplete;

        public event DetachErrorEventHander DetachError;

        public event RestoreCompleteEventHander RestoreComplete;

        public event RestoreErrorEventHander RestoreError;

        public event RestoreProcessEventHander RestoreProcess;

        private event ServerReloadEventHander ServerReload;

        public event UpdateCompleteEventHandler UpdateComplete;

        public event UpdateErrorEventHandler UpdateError;

        public event UpdateProcessEventHandler UpdateProcess;

        public void Attach(string db, string mdffile)
        {
            try
            {
                SqlHelper helper = new SqlHelper(_mConnectString);
                if (helper.Exists(db) != "OK")
                {
                    this.RaiseAttachErrorEventHander("Kh\x00f4ng thể đăng k\x00fd được cơ sở dữ liệu.\nChi tiết:\n\tCơ sỡ dữ liệu đ\x00e3 tồn tại.");
                }
                else
                {
                    string str = helper.Open();
                    if (str != "OK")
                    {
                        this.RaiseAttachErrorEventHander("Kh\x00f4ng thể đăng k\x00fd được cơ sở dữ liệu.\nChi tiết:\n\t" + str);
                    }
                    else
                    {
                        ServerConnection serverConnection = new ServerConnection(helper.Connection);
                        Server server = new Server(serverConnection);
                        StringCollection strings2 = new StringCollection();
                        strings2.Add(server.EnumDetachedDatabaseFiles(mdffile)[0]);
                        strings2.Add(server.EnumDetachedLogFiles(mdffile)[0]);
                        StringCollection files = strings2;
                        server.AttachDatabase(db, files);
                        this.RaiseAttachCompleteEventHander();
                    }
                }
            }
            catch (Exception exception)
            {
                this.RaiseAttachErrorEventHander("Kh\x00f4ng thể đăng k\x00fd được cơ sở dữ liệu.\nChi tiết:\n\t" + exception.Message);
            }
        }

        private void backup_Complete(object sender, ServerMessageEventArgs e)
        {
            this.RaiseBackupCompleteEventHander(e);
        }

        private void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            this.RaiseBackupProcessEventHander(e);
        }

        public void BackupDataBase(string databaseName, string destinationPath)
        {
            try
            {
                SqlConnection.ClearAllPools();
                SqlConnection sqlConnection = new SqlConnection(_mConnectString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server srv = new Server(serverConnection);
                Backup backup = new Backup
                {
                    Action = BackupActionType.Database,
                    Database = databaseName
                };
                backup.Devices.Add(new BackupDeviceItem(destinationPath, DeviceType.File));
                backup.Initialize = true;
                backup.Checksum = true;
                backup.ContinueAfterError = true;
                backup.Incremental = false;
                backup.LogTruncation = BackupTruncateLogType.Truncate;
                backup.PercentComplete += new PercentCompleteEventHandler(this.backup_PercentComplete);
                backup.Complete += new ServerMessageEventHandler(this.backup_Complete);
                backup.SqlBackup(srv);
                sqlConnection.Close();
            }
            catch (FailedOperationException)
            {
                this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể sao lưu dữ liệu.\nChi Tiết:\n\tThư mục sao lưu đ\x00e3 được bảo vệ, vui l\x00f2ng chọn thư mục kh\x00e1c.");
            }
            catch (Exception exception2)
            {
                if (exception2.Message.IndexOf("failed for Server") != -1)
                {
                    this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể sao lưu dữ liệu.\nChi Tiết:\n\tThư mục sao lưu đ\x00e3 được bảo vệ, vui l\x00f2ng chọn thư mục kh\x00e1c.");
                }
                else
                {
                    this.RaiseBackupErrorEventHander(exception2.Message);
                }
            }
        }

        public SqlConnection Connection(string serverConnectionString)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection connection = new SqlConnection(serverConnectionString);
            try
            {
                connection.Open();
            }
            catch
            {
                this.RaiseDatabaseErrorEventHander("Kh\x00f4ng thể kết nối được m\x00e1y chủ.");
                return connection;
            }
            finally
            {
                Cursor.Current = current;
            }
            return connection;
        }

        public static bool CorrectConnection(string serverConnectionString)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            using (SqlConnection connection = new SqlConnection(serverConnectionString))
            {
                try
                {
                    connection.Open();
                    connection.Close();
                }
                catch
                {
                    return false;
                }
                finally
                {
                    Cursor.Current = current;
                }
            }
            return true;
        }

        public void Created(string source, string desc, string database)
        {
            try
            {
                FileInfo info = new FileInfo(source);
                if (!info.Exists)
                {
                    this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể tạo được cơ sở dữ liệu.\nChi Tiết:\n\tCở dữ liệu nguồn kh\x00f4ng tồn tại vui l\x00f2ng c\x00e0i đặt lại phần mềm");
                }
                else if (!Directory.Exists(desc))
                {
                    this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể tạo được cơ sở dữ liệu.\nChi Tiết:\n\tThư mục tạo cơ sở dữ liệu kh\x00f4ng tồn tại.Vui l\x00f2ng tạo hay chọn một thư mục kh\x00e1c.");
                }
                else
                {
                    string name = source;
                    string str2 = database;
                    string str3 = desc;
                    SqlConnection sqlConnection = new SqlConnection(_mConnectString);
                    sqlConnection.Open();
                    ServerConnection serverConnection = new ServerConnection(sqlConnection);
                    Server srv = new Server(serverConnection);
                    Restore restore = new Restore
                    {
                        Database = str2
                    };
                    restore.Devices.AddDevice(name, DeviceType.File);
                    DataTable table = restore.ReadFileList(srv);
                    string logicalFileName = "ERP";
                    string str5 = "ERP_Log";
                    if (table == null)
                    {
                        this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể tạo được cơ sở dữ liệu.\nChi Tiết:\n\tTập tin cơ sở dữ liệu nguồn kh\x00f4ng đ\x00fang, vui l\x00f2ng c\x00e0i đặt lại phần mềm.");
                    }
                    else
                    {
                        if (table.Rows.Count != 0)
                        {
                            logicalFileName = table.Rows[0][0].ToString();
                            str5 = table.Rows[1][0].ToString();
                        }
                        string physicalFileName = str3 + @"\" + str2 + ".mdf";
                        string str7 = str3 + @"\" + str2 + "_log.ldf";
                        restore.RelocateFiles.Add(new RelocateFile(logicalFileName, physicalFileName));
                        restore.RelocateFiles.Add(new RelocateFile(str5, str7));
                        restore.ReplaceDatabase = true;
                        restore.PercentCompleteNotification = 10;
                        restore.PercentComplete += new PercentCompleteEventHandler(this.myRestore_PercentComplete);
                        restore.Complete += new ServerMessageEventHandler(this.myRestore_Complete);
                        restore.SqlRestore(srv);
                        sqlConnection.Close();
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception.Message.IndexOf("failed for Server") != -1)
                {
                    this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể tạo được cơ sở dữ liệu.\nChi Tiết:\n\tThư mục tạo cơ sở dữ liệu đ\x00e3 được bảo vệ, vui l\x00f2ng chọn thư mục kh\x00e1c.");
                }
                else
                {
                    this.RaiseCreatedErrorEventHander("Kh\x00f4ng thể tạo được cơ sở dữ liệu.\nChi Tiết:\n\t" + exception.Message);
                }
            }
        }

        public void Deleted(string database)
        {
            try
            {
                SqlConnection sqlConnection = new SqlConnection(_mConnectString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server server = new Server(serverConnection);
                server.KillAllProcesses(database);
                server.KillDatabase(database);
                this.RaiseDeletedCompleteEventHander();
                sqlConnection.Close();
            }
            catch (Exception exception)
            {
                this.RaiseDeletedErrorEventHander(exception.Message);
            }
        }

        public void Detach(string database)
        {
            try
            {
                SqlConnection sqlConnection = new SqlConnection(_mConnectString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server server = new Server(serverConnection);
                server.KillAllProcesses(database);
                server.DetachDatabase(database, true);
                this.RaiseDetachCompleteFinishEventHander();
                sqlConnection.Close();
            }
            catch (Exception exception)
            {
                this.RaiseDetachErrorEventHander(exception.Message);
            }
        }

        public DataTable GetAllDatabase(string server, string user, string password, bool auth)
        {
            string serverConnectionString = string.Format("data source={0};integrated security=SSPI;Initial Catalog=master;", server);
            if (!auth)
            {
                serverConnectionString = string.Format("server={0};user id={1};password={2};", server, user, password);
            }
            Cursor.Current = Cursors.WaitCursor;
            DataTable table = new DataTable();
            table.Columns.Add("Database");
            SqlConnection sqlConnection = this.Connection(serverConnectionString);
            try
            {
                if (sqlConnection.State != ConnectionState.Open)
                {
                    return table;
                }
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server server2 = new Server(serverConnection);
                foreach (Database database in server2.Databases)
                {
                    if (!database.IsSystemObject)
                    {
                        table.Rows.Add(new object[] { database.Name });
                        DATA data = new DATA(database.Name, database.Version.ToString(), database.CreateDate, database.PrimaryFilePath);
                        this.RaiseDatabaseFoundEventHander(data);
                    }
                }
            }
            catch (Exception exception)
            {
                this.RaiseDatabaseErrorEventHander(exception.Message);
            }
            finally
            {
                sqlConnection.Close();
            }
            this.RaiseDatabaseCompleteEventHander(table);
            return table;
        }

        public DataTable GetDatabase(SqlConnection mySqlConnection)
        {
            ServerConnection serverConnection = new ServerConnection(mySqlConnection);
            Server server = new Server(serverConnection);
            DataTable table = new DataTable();
            table.Columns.Add("STT");
            table.Columns.Add("Database");
            table.Columns.Add("Version");
            table.Columns.Add("Created");
            table.Columns.Add("Path");
            this.RaiseDatabasePercentEventHander(0);
            int num = 0;
            SYS_INFO sys_info = new SYS_INFO();
            foreach (Database database in server.Databases)
            {
                try
                {
                    if (!database.IsSystemObject && (database.Tables["SYS_INFO"] != null))
                    {
                        num++;
                        this.RaiseDatabasePercentEventHander(((int)(((double)num) / ((double)server.Databases.Count))) * 100);
                        DATA data = new DATA(database.Name, database.Version.ToString(), database.CreateDate, database.PrimaryFilePath);
                        object[] values = new object[] { table.Rows.Count + 1, database.Name, sys_info.Version, database.CreateDate, database.PrimaryFilePath };
                        this.RaiseDatabaseFoundEventHander(data);
                        table.Rows.Add(values);
                    }
                }
                catch
                {
                }
            }
            return table;
        }

        public DataTable GetDatabase(string server)
        {
            SqlHelper helper = new SqlHelper();
            return this.GetDatabase(new SqlConnection(helper.RebuildConnectionString(server)));
        }

        public DataTable GetDatabase(string server, string user, string pass)
        {
            return this.GetDatabase(new SqlConnection(new SqlHelper().RebuildConnectionString(server, user, pass)));
        }

        public DataTable GetServer()
        {
            return this.GetServer(true);
        }

        private DataTable GetServer(bool localOnly)
        {
            DataTable data = SmoApplication.EnumAvailableSqlServers(localOnly);
            this.RaiseServerReloadEventHander(data);
            return data;
        }

        private void myRestore_Complete(object sender, ServerMessageEventArgs e)
        {
            this.RaiseCreatedCompleteEventHander(e);
        }

        private void myRestore_Complete1(object sender, ServerMessageEventArgs e)
        {
            this.RaiseRestoreCompleteEventHander(e);
        }

        private void myRestore_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            this.RaiseCreatedProcessEventHander(e);
        }

        private void myRestore_PercentComplete1(object sender, PercentCompleteEventArgs e)
        {
            this.RaiseRestoreProcessEventHander(e);
        }

        private void RaiseAttachCompleteEventHander()
        {
            if (this.AttachComplete != null)
            {
                this.AttachComplete(this);
            }
        }

        private void RaiseAttachErrorEventHander(string message)
        {
            if (this.AttachError != null)
            {
                this.AttachError(this, message);
            }
        }

        private void RaiseBackupCompleteEventHander(ServerMessageEventArgs e)
        {
            if (this.BackupComplete != null)
            {
                this.BackupComplete(this, e);
            }
        }

        private void RaiseBackupErrorEventHander(string message)
        {
            if (this.BackupError != null)
            {
                this.BackupError(this, message);
            }
        }

        private void RaiseBackupProcessEventHander(PercentCompleteEventArgs e)
        {
            if (this.BackupProcess != null)
            {
                this.BackupProcess(this, e);
            }
        }

        private void RaiseCreatedCompleteEventHander(ServerMessageEventArgs e)
        {
            if (this.CreatedComplete != null)
            {
                this.CreatedComplete(this, e);
            }
        }

        private void RaiseCreatedErrorEventHander(string message)
        {
            if (this.CreatedError != null)
            {
                this.CreatedError(this, message);
            }
        }

        private void RaiseCreatedProcessEventHander(PercentCompleteEventArgs e)
        {
            if (this.CreatedProcess != null)
            {
                this.CreatedProcess(this, e);
            }
        }

        private void RaiseDatabaseCompleteEventHander(DataTable data)
        {
            if (this.DatabaseComplete != null)
            {
                this.DatabaseComplete(this, data);
            }
        }

        private void RaiseDatabaseErrorEventHander(string message)
        {
            if (this.DatabaseError != null)
            {
                this.DatabaseError(this, message);
            }
        }

        private void RaiseDatabaseFoundEventHander(DATA data)
        {
            if (this.DatabaseFound != null)
            {
                this.DatabaseFound(this, data);
            }
        }

        private void RaiseDatabasePercentEventHander(int e)
        {
            if (this.DatabasePercent != null)
            {
                this.DatabasePercent(this, e);
            }
        }

        private void RaiseDeletedCompleteEventHander()
        {
            if (this.DeletedComplete != null)
            {
                this.DeletedComplete(this);
            }
        }

        private void RaiseDeletedErrorEventHander(string message)
        {
            if (this.DeletedError != null)
            {
                this.DeletedError(this, message);
            }
        }

        private void RaiseDetachCompleteFinishEventHander()
        {
            if (this.DetachComplete != null)
            {
                this.DetachComplete(this);
            }
        }

        private void RaiseDetachErrorEventHander(string message)
        {
            if (this.DetachError != null)
            {
                this.DetachError(this, message);
            }
        }

        private void RaiseRestoreCompleteEventHander(ServerMessageEventArgs e)
        {
            if (this.RestoreComplete != null)
            {
                this.RestoreComplete(this, e);
            }
        }

        private void RaiseRestoreErrorEventHander(string message)
        {
            if (this.RestoreError != null)
            {
                this.RestoreError(this, message);
            }
        }

        private void RaiseRestoreProcessEventHander(PercentCompleteEventArgs e)
        {
            if (this.RestoreProcess != null)
            {
                this.RestoreProcess(this, e);
            }
        }

        private void RaiseServerReloadEventHander(DataTable data)
        {
            if (this.ServerReload != null)
            {
                this.ServerReload(this, data);
            }
        }

        private void RaiseUpdateCompleteEventHandler()
        {
            if (this.UpdateComplete != null)
            {
                this.UpdateComplete(this);
            }
        }

        private void RaiseUpdateErrorEventHandler(string message)
        {
            if (this.UpdateError != null)
            {
                this.UpdateError(this, message);
            }
        }

        private void RaiseUpdateProcessEventHandler(string message)
        {
            if (this.UpdateProcess != null)
            {
                this.UpdateProcess(this, message);
            }
        }

        public void RestoreDatabase(string backupFilePath, string destinationDatabaseName)
        {
            try
            {
                SqlConnection sqlConnection = new SqlConnection(_mConnectString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server srv = new Server(serverConnection);
                Restore restore = new Restore
                {
                    Database = destinationDatabaseName
                };
                Database database = srv.Databases[destinationDatabaseName];
                if (database != null)
                {
                    srv.KillAllProcesses(destinationDatabaseName);
                }
                restore.Devices.AddDevice(backupFilePath, DeviceType.File);
                restore.ReplaceDatabase = true;
                restore.PercentCompleteNotification = 10;
                restore.Complete += new ServerMessageEventHandler(this.myRestore_Complete1);
                restore.PercentComplete += new PercentCompleteEventHandler(this.myRestore_PercentComplete1);
                restore.SqlRestore(srv);
                srv.Databases[destinationDatabaseName].SetOnline();
                sqlConnection.Close();
            }
            catch (Exception exception)
            {
                this.RaiseRestoreErrorEventHander(exception.Message);
            }
        }

        public void UpdateDatabase(string _mRequestVersion)
        {
            SYS_INFO sys_info = new SYS_INFO();
            sys_info.Get();
            if (Directory.Exists(Application.StartupPath + @"\Update\UpdateDatabase\" + sys_info.Version))
            {
                ArrayList list = new ArrayList();
                string[] directories = Directory.GetDirectories(Application.StartupPath + @"\Update\UpdateDatabase");
                IComparer comparer = new FileComparer(FileComparer.CompareBy.Name);
                Array.Sort(directories, comparer);
                foreach (string str in directories)
                {
                    string[] strArray2 = str.Split(new char[] { '\\' });
                    if ((string.Compare(strArray2[strArray2.Length - 1], sys_info.Version) >= 0) && (string.Compare(strArray2[strArray2.Length - 1], _mRequestVersion) < 0))
                    {
                        Thread.Sleep(0x7d0);
                        ArrayList list2 = new ArrayList();
                        string[] array = Directory.GetFiles(str, "*.sql", SearchOption.TopDirectoryOnly);
                        IComparer comparer2 = new FileComparer(FileComparer.CompareBy.Name);
                        Array.Sort(array, comparer2);
                        if (array.Length > 0)
                        {
                            ThreadStart start = null;
                            foreach (string file in array)
                            {
                                try
                                {
                                    this.RaiseUpdateProcessEventHandler(file.ToString());
                                }
                                catch
                                {
                                }
                                if (start == null)
                                {
                                    start = () => this.UpdateVersion(file);
                                }
                                Thread thread = new Thread(start);
                                thread.Start();
                                thread.Join();
                            }
                        }
                        Thread.Sleep(0xbb8);
                    }
                }
                this.RaiseUpdateCompleteEventHandler();
            }
            else
            {
                try
                {
                    string message = ">>>>>>Phi\x00ean bản dữ liệu hiện tại kh\x00f4ng được hổ trợ để n\x00e2ng cấp l\x00ean phi\x00ean bản mới! Vui l\x00f2ng li\x00ean hệ với ch\x00fang t\x00f4i để được hổ trợ.";
                    this.RaiseUpdateErrorEventHandler(message);
                }
                catch
                {
                }
            }
        }

        private string UpdateVersion(string file)
        {
            string str = "";
            StreamReader reader = new StreamReader(file);
            SqlHelper helper = new SqlHelper
            {
                CommandType = CommandType.Text
            };
            helper.Extract();
            str = helper.ExecuteNonQuery(reader.ReadToEnd());
            reader.Close();
            return str;
        }

        public static string ConnectString
        {
            get
            {
                return _mConnectString;
            }
            set
            {
                _mConnectString = value;
            }
        }

        public class DataMaker
        {
            public static string AutoBackup()
            {
                string path = GetLastDrive() + "Backup";
                SqlHelper helper = new SqlHelper();
                string fileName = string.Concat(new object[] { helper.Database, DateTime.Now.Day, ".", DateTime.Now.Month, ".", DateTime.Now.Year, ".", DateTime.Now.Hour, ".", DateTime.Now.Minute, ".", DateTime.Now.Second });
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string str4 = Backup(path, fileName);
                if (str4 != "OK")
                {
                    MessageBox.Show("Lỗi" + str4, "Th\x00f4ng b\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                return str4;
            }

            private static string Backup(string path, string fileName)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                SqlHelper helper = new SqlHelper();
                string commandText = "BACKUP DATABASE " + helper.Database + " TO  DISK = N'" + path + @"\" + fileName + "' WITH  INIT ,  NOUNLOAD ,  NAME = N'" + fileName + "backup',  NOSKIP ,  STATS = 10,  NOFORMAT";
                return helper.ExecuteNonQuery(commandText);
            }

            private static string Delete(string path)
            {
                FileInfo info = new FileInfo(path);
                if (info.Exists)
                {
                    try
                    {
                        info.Delete();
                    }
                    catch (Exception exception)
                    {
                        return exception.Message;
                    }
                }
                return "OK";
            }

            public static string GetLastDrive()
            {
                string[] logicalDrives = Environment.GetLogicalDrives();
                for (int i = logicalDrives.Length - 1; i > 0; i--)
                {
                    DriveInfo info = new DriveInfo(logicalDrives[i]);
                    if (info.DriveType == DriveType.Fixed)
                    {
                        return info.Name;
                    }
                }
                return "C:";
            }

            public static string Maker(string server, string userid, string password, string database, string FolderData, bool authen)
            {
                string str3;
                SqlHelper helper = new SqlHelper(server, "master", userid, password, authen);
                if (helper.Exists(database) != "OK")
                {
                    return "Cơ Sở Dữ Liệu đ\x00e3 tồn tại.";
                }
                string path = FolderData + @"\" + database + "_DATA.mdf";
                string str2 = FolderData + @"\" + database + "_Log.ldf";
                if (!Directory.Exists(FolderData))
                {
                    Directory.CreateDirectory(FolderData);
                }
                try
                {
                    if (!Directory.Exists(FolderData))
                    {
                        Directory.CreateDirectory(FolderData);
                    }
                    int num = 0;
                    while (File.Exists(path))
                    {
                        num++;
                        path = string.Concat(new object[] { FolderData, @"\", database, num, "_DATA.mdf" });
                    }
                    num = 0;
                    while (File.Exists(str2))
                    {
                        num++;
                        str2 = string.Concat(new object[] { FolderData, @"\", database, num, "_Log.ldf" });
                    }
                    File.Copy(Application.StartupPath + @"\data.mdf", path);
                    File.Copy(Application.StartupPath + @"\data.ldf", str2);
                    SqlConnection.ClearAllPools();
                    str3 = helper.Attach(path, str2, database);
                    if (str3 != "OK")
                    {
                        Delete(path);
                        Delete(str2);
                    }
                }
                catch (Exception exception)
                {
                    return exception.Message;
                }
                return str3;
            }

            public static string MakerExample(string server, string userid, string password, string database, string FolderData, bool Authen)
            {
                string str3;
                SqlHelper helper = new SqlHelper(server, "master", userid, password, Authen);
                if (helper.Exists(database) != "OK")
                {
                    return "Cơ Sở Dữ Liệu đ\x00e3 tồn tại.";
                }
                string path = FolderData + @"\" + database + "_DATA.mdf";
                string str2 = FolderData + @"\" + database + "_Log.ldf";
                if (!Directory.Exists(FolderData))
                {
                    Directory.CreateDirectory(FolderData);
                }
                try
                {
                    if (!Directory.Exists(FolderData))
                    {
                        Directory.CreateDirectory(FolderData);
                    }
                    int num = 0;
                    while (File.Exists(path))
                    {
                        num++;
                        path = string.Concat(new object[] { FolderData, @"\", database, num, "_DATA.mdf" });
                    }
                    num = 0;
                    while (File.Exists(str2))
                    {
                        num++;
                        str2 = string.Concat(new object[] { FolderData, @"\", database, num, "_Log.ldf" });
                    }
                    File.Copy(Application.StartupPath + @"\HRMExample.mdf", path);
                    File.Copy(Application.StartupPath + @"\HRMExample.ldf", str2);
                    SqlConnection.ClearAllPools();
                    str3 = helper.Attach(path, str2, database);
                    if (str3 != "OK")
                    {
                        Delete(path);
                        Delete(str2);
                    }
                }
                catch (Exception exception)
                {
                    return exception.Message;
                }
                return str3;
            }

            public static string SimpleMaker(string server, string userid, string password, string database, string folderData, bool authen)
            {
                string str3;
                Exception exception;
                string path = folderData + @"\" + database + "_DATA.mdf";
                string str2 = folderData + @"\" + database + "_Log.ldf";
                try
                {
                    try
                    {
                        File.Delete(path);
                        File.Delete(str2);
                    }
                    catch (Exception exception1)
                    {
                        exception = exception1;
                    }
                    if (!Directory.Exists(folderData))
                    {
                        Directory.CreateDirectory(folderData);
                    }
                    if (!File.Exists(path) & !File.Exists(str2))
                    {
                        File.Copy(Application.StartupPath + @"\Simple.mdf", path);
                        File.Copy(Application.StartupPath + @"\Simple.ldf", str2);
                    }
                    else
                    {
                        return "C\x00f3 thể cơ sở dữ liệu n\x00e0y đ\x00e3 tồn tại rồi\n\nHay do c\x00f3 tồn tại tập tin cơ sở dữ liệu tr\x00f9ng nhau\n\nVui l\x00f2ng chọn đường dẫn kh\x00e1c hoặc đặt t\x00ean cơ sở dữ liệu kh\x00e1c.";
                    }
                    SqlConnection.ClearAllPools();
                    str3 = new SqlHelper(server, "master", userid, password, authen).Attach(path, str2, database);
                    if (str3 == "OK")
                    {
                        SqlHelper helper2 = new SqlHelper(server, database, userid, password, authen);
                    }
                    else
                    {
                        File.Delete(path);
                        File.Delete(str2);
                    }
                }
                catch (Exception exception2)
                {
                    exception = exception2;
                    return exception.Message;
                }
                return str3;
            }
        }
    }

}
